package org.richin.support.biz;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;

import javax.persistence.Transient;

import org.richin.support.orm.DaoSupport;
import org.richin.support.orm.Page;
import org.richin.web.struts1.service.IValueObjectBaseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.utils.ReflectionUtils;

@Transactional
@SuppressWarnings("unchecked")
public abstract class EntityManager<T, ID extends Serializable> implements IValueObjectBaseService<T> {
	protected Logger logger = LoggerFactory.getLogger(super.getClass());
	protected Class<T> entityClass;

	public EntityManager() {
		this.entityClass = ReflectionUtils.getSuperClassGenricType(super.getClass());
	}

	protected abstract DaoSupport<T, ID> getDaoSupport();

	@Transactional(readOnly = true)
	public T get(Serializable id) {
		return getDaoSupport().get((ID) id);
	}

	@Transient
	public String getIdName() {
		return getDaoSupport().getIdName(entityClass);
	}

	@Transactional(readOnly = true)
	public Page<T> getAll(Page<T> page) {
		return getDaoSupport().getAll(page);
	}

	@Transactional(readOnly = true)
	public List<T> getAll() {
		return getDaoSupport().getAll();
	}

	/*
	 * @Transactional(readOnly=true) public Page<T> search(Page<T> page, List<PropertyFilter>
	 * filters) { return getDaoSupport().findByFilters(page, filters); }
	 */
	@Transactional(rollbackFor = ServiceException.class)
	public void save(T entity) {
		logger.info("开始保存.............");
		getDaoSupport().save(entity);
	}

	public void delete(Serializable id) {
		getDaoSupport().delete((ID) id);
	}

	public void delete(T entity) {
		getDaoSupport().delete(entity);

	}

	public void saveAll(Collection<T> entities) {
		getDaoSupport().saveAll(entities);
	}

	public void deleteByIds(Serializable[] ids) {
		getDaoSupport().delete((ID[]) ids);
	}
	@Transactional(readOnly = true)
	public List<T> findBy(String propertyName, Object value) {
		return getDaoSupport().findByProperty(propertyName, value);
	}
	@Transactional(readOnly = true)
	public List<T> findByLike(String propertyName, String value) {
		return getDaoSupport().findByLike(propertyName, value);
	}
	@Transactional(readOnly = true)
	public T findUniqueBy(String propertyName, Object value) {
		return getDaoSupport().findByUnique(propertyName, value);
	}
	@Transactional(readOnly = true)
	public boolean isNotUnique(T entity, String names) {
		return getDaoSupport().isNotUnique(entity, names);
	}

}
